<template>
  <iframe
    id="aliyunPreview"
    src="https://preview.imm.aliyun.com/index.html"
    allowfullscreen
    frameborder="0"
    scrolling="no"
  ></iframe>
</template>

<script>
import { asyncossupload ,asyncInquireusertotpdataid} from "../plugins/api.js";
import { mapActions  } from "vuex";
export default {
  name: "app",
  async beforeMount() {
    let x;
    try {
      x = await this.session();
      if (!x) {
        location.href = "/";
      }
    } catch (e) {
      location.href = "/";
    }
  },
  mounted() {
    window.sendMessage = (action, data) => {
      var test = document.getElementById("aliyunPreview");
      test.contentWindow.postMessage(
        this.json2str({
          action: action,
          data: data
        }),
        "*"
      );
    };
    window.addEventListener(
      "message",
      e => {
        let res;
        if (e.data && typeof e.data === "string") {
          res = JSON.parse(e.data);
          switch (res.action) {
            case "preview.ready":
              this.init();
              break;
            case "logic.refreshToken":
              window.sendMessage("logic.setToken", this.setToken());
              break;
            case "message.error":
              break;
          }
        }
      },
      false
    );
  },
  methods: {
    ...mapActions(["session"]),
    async init() {
      const ID = location.search.split("=")[1];
      const arr = await asyncInquireusertotpdataid({tpdata_ID:ID})
      const url =arr.fileurl;
      if(arr){
        const {
          accessKeyId,
          accessKeySecret,
          securityToken
        } = await asyncossupload();
        window.sendMessage("preview.init", {
          url,
          region: "oss-cn-beijing",
          bucket: "hterobot-pdf",
          accessKeyId,
          accessKeySecret,
          stsToken: securityToken
        });
      }else{
         this.$message({
              message: "没有权限哦！",
              type: "success"
            });
      }
    },
    async setToken() {
      const data = await asyncossupload();
      return {
        region: "oss-cn-beijing",
        accessKeyId: data.accessKeyId,
        accessKeySecret: data.accessKeySecret,
        stsToken: data.securityToken,
        bucket: "hterobot-pdf"
      };
    },
    json2str(obj) {
      return JSON.stringify(obj, function(key, val) {
        if (typeof val === "function") {
          val = val.toString();
        }
        return val;
      });
    },
    parse(params) {
      return Object.keys(params)
        .map(key => {
          return `${key}=${encodeURIComponent(params[key])}`;
        })
        .join("&");
    }
  }
};
</script>


<style>
</style>

